/*
 * action 类型
 */
import { getUrl, postUrl, getUrlProxy } from '../config/config';
import Request from '../util/Request';

export const REQUEST_POSTS = 'REQUEST_POSTS';
export const RECEIVE_POSTS = 'RECEIVE_POSTS';

export function requestPosts() {
    return {
        type: REQUEST_POSTS
    }
}

export function receivePosts(res) {
    return {
        type: RECEIVE_POSTS,
        res: res,
        receivedAt: Date.now()
    }
}

export function fetchPosts(fetchConf) {
    return function (dispatch) {
        dispatch(requestPosts())
        var type = fetchConf.type;
        var id = fetchConf.id;
        var url;
        var Req = new Request();
        switch (type) {
            case 'getUrl': {
                url = getUrl + '?id=' + id;
                return Req.get(url).then(res => {
                    let _res = JSON.stringify(res)
                    dispatch(receivePosts(_res));
                })
            }
            case 'postUrl': {
                url = postUrl;
                var data = { id: id, };
                return Req.post(url, data).then(res => {
                    let _res = JSON.stringify(res)
                    dispatch(receivePosts(_res));
                })
            }
            case 'getUrlProxy': {
                url = getUrlProxy + '?id=' + id;
                return Req.get(url).then(res => {
                    let _res = JSON.stringify(res)
                    dispatch(receivePosts(_res));
                })
            }
        }
    }
}

export function fetchPostsIfNeeded(fetchConf) {
    return (dispatch, getState) => {
        return dispatch(fetchPosts(fetchConf))
        // let isFetched = getState().isFetched;
        // if (isFetched) {
        //     return dispatch(fetchPosts(fetchConf))
        // } else {
        //     return getState()
        // }
    }
}